export function arrayToTreeArray<T>(
  array: any[],
  keyMapping = {
    id: "id",
    pid: "pid",
    children: "children",
  }
) {
  const { id, pid, children } = keyMapping;
  const idMap: Recordable = {};
  const result = [];

  array.forEach((item) => {
    idMap[item[id]] = item;
  });
  array.forEach((item) => {
    if (!item[pid] || item[pid] < 0) return;
    const parent = idMap[item[pid]];
    if (parent[children]) parent[children].push(item);
    else parent[children] = [item];
  });
  for (const key in idMap) {
    if (!idMap[key][pid] || idMap[key][pid] < 0) {
      result.push(idMap[key]);
    }
  }
  return result as T[];
}
